<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        /* 
            从个位到十位到百位依次进行，根据数字的基数，将其放到指定的桶，再push到nums的数组
        */

        // 找到最大的位数
        function findMaxValue(nums) {
            var max = nums[0];
            for (var i = 0; i < nums.length; i++) {
                if (nums[i] > max) {
                    max = nums[i]
                }
            }
            return max
        }

        function radixSort(nums) {
            // 找到里面的最大位数
            let count = String(findMaxValue(nums)).length

            // 标志位
            let significant = 1

            while (count > 0) {
                // 0-9长度至多是10
                let bucket = new Array(10).fill(0).map(() => [])
                // 根据位数把元素放到对应的桶里面去
                for (let i = 0; i < nums.length; i++) {
                    // 根据位数让他放到指定的桶
                    let digit = Math.floor(nums[i] / significant) % 10
                    bucket[digit].push(nums[i])
                }
                // 清空原数组
                nums.length = 0;
                for (let i = 0; i < bucket.length; i++) {
                    for (let j = 0; j < bucket[i].length; j++) {
                        nums.push(bucket[i][j])
                    }
                }
                significant *= 10
                count--
            }
            return nums
        }
        console.log(radixSort([3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]));
    </script>
</body>

</html>